package com.jcl.recruit.wechat.logic;

import com.jcl.core.utils.StringUtils;
import com.jcl.recruit.core.config.SystemConfig;
import com.jcl.recruit.core.constants.UserExternalLoginConstant;
import com.jcl.recruit.crawler.logic.CrawlerDownloadTaskLogic;
import com.jcl.recruit.crawler.model.CrawlerDownloadTask;
import com.jcl.recruit.resume.logic.ResumePersInfoLogic;
import com.jcl.recruit.resume.model.ResumePersInfo;
import com.jcl.recruit.searchresume.logic.SearchResumeRecordLogic;
import com.jcl.recruit.searchresume.model.SearchResumeRecord;
import com.jcl.recruit.user.logic.UserExternalAccessLogic;
import com.jcl.recruit.user.model.UserExternalAccess;
import com.jcl.recruit.wechat.utils.WechatUtils;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

@Component
public class WechatPushCrawlerLogic {

    @Autowired
    private CrawlerDownloadTaskLogic crawlerDownloadTaskLogic;

    @Autowired
    private UserExternalAccessLogic userExternalAccessLogic;

    @Autowired
    private SearchResumeRecordLogic searchResumeRecordLogic;

    @Autowired
    private ResumePersInfoLogic resumePersInfoLogic;


    public int pushDownloadResumeMessage(String corpCode, String userId, Integer resumeId) {

        List<CrawlerDownloadTask> taskList = crawlerDownloadTaskLogic.findListByResumeId(corpCode, resumeId);
        if (CollectionUtils.isNotEmpty(taskList)) {
            CrawlerDownloadTask task = taskList.get(0);
            ResumePersInfo persInfo = resumePersInfoLogic.findOne(corpCode, resumeId);
            if (null != persInfo) {
                UserExternalAccess userAccess = userExternalAccessLogic.findOneByUserId(Integer.valueOf(userId),
                        UserExternalLoginConstant.USER_ACCESS_CATEGORY_WECHAT);
                if (null != userAccess) {
                    List<SearchResumeRecord> recordList = searchResumeRecordLogic.selectWechatPushRecordByUserId(userAccess.getUserId());
                    WechatUtils.TemplateInfo templateInfo = WechatPushCrawlerLogic.mdTemplateInfo(
                            persInfo, task, userAccess, recordList);
                    send(templateInfo);
                    return 1;
                }
            }
        }
        return 0;
    }

    public static WechatUtils.TemplateInfo mdTemplateInfo(ResumePersInfo persInfo,
                                                          CrawlerDownloadTask task,
                                                          UserExternalAccess userAccess,
                                                          List<SearchResumeRecord> recordList) {

        WechatUtils.TemplateInfo templateInfo = new WechatUtils.TemplateInfo();

        templateInfo.setTouser(userAccess.getExternalKey());
        String redirectUrl = null;
        try {
            redirectUrl = URLEncoder.encode(SystemConfig.getSystemWebUrl() + SystemConfig.getWechatLoginUrl(),
                    "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        String url = WechatUtils.getWechatLoginUrl(SystemConfig.getSystemWechatAppid(),
                redirectUrl, WechatUtils.LOGIN_STATE + WechatUtils.LOGIN_STATE_SPLIT +
                        WechatUtils.LOGIN_STATE_CRAWLER_DOWNLOAD);

        templateInfo.setUrl(url);
        templateInfo.setTemplate_id(SystemConfig.getWechatTemplateDownloadResumeId());

        WechatUtils.TemplateCrawlingCompleteInfo screenInfo = getTemplateData(userAccess,
                persInfo, task, recordList);
        templateInfo.setData(screenInfo);

        return templateInfo;
    }

    public static WechatUtils.TemplateCrawlingCompleteInfo getTemplateData(UserExternalAccess userAccess,
                                                                           ResumePersInfo persInfo,
                                                                           CrawlerDownloadTask task,
                                                                           List<SearchResumeRecord> recordList) {

        String keyword1 = "请设置推荐条件";

        StringBuffer _keyword1 = new StringBuffer();
        if (CollectionUtils.isNotEmpty(recordList)) {
            List<String> keywords = new ArrayList<>();
            List<String> educations = new ArrayList<>();
            List<String> cities = new ArrayList<>();
            for (SearchResumeRecord record : recordList) {
                if (StringUtils.hasLength(record.getKeyword()) && !keywords.contains(record.getKeyword())) {
                    keywords.add(record.getKeyword());
                }
                if (StringUtils.hasLength(record.getEducation()) && !educations.contains(record.getEducation())) {
                    educations.add(record.getEducation());
                }
                if (StringUtils.hasLength(record.getCity()) && !cities.contains(record.getCity())) {
                    cities.add(record.getCity());
                }
            }
            if (keywords.isEmpty() && educations.isEmpty() && cities.isEmpty()) {
            } else {
                if (!keywords.isEmpty()) {
                    String temp = keywords.toString();
                    _keyword1.append(" ").append(temp.substring(1, temp.length() - 1)).append(" |");
                }
                if (!educations.isEmpty()) {
                    String temp = educations.toString();
                    _keyword1.append(" ").append(temp.substring(1, temp.length() - 1)).append(" |");
                }
                if (!cities.isEmpty()) {
                    String temp = cities.toString();
                    _keyword1.append(" ").append(temp.substring(1, temp.length() - 1)).append(" |");
                }

            }
            if (_keyword1.length() > 0) {
                keyword1 = _keyword1.toString().substring(0, _keyword1.length() - 1);
            }
        }

        String keyword2 = "";
        StringBuffer _keyword2 = new StringBuffer();
        if (StringUtils.hasLength(persInfo.getName())) {
            _keyword2.append(persInfo.getName()).append(" | ");
        }
        if (StringUtils.hasLength(persInfo.getSex())) {
            _keyword2.append(persInfo.getSex()).append(" | ");
        }
        if (StringUtils.hasLength(persInfo.getMobile())) {
            _keyword2.append(persInfo.getMobile()).append(" | ");
        }
        if (_keyword2.length() > 0) {
            keyword2 = _keyword2.toString().substring(0, _keyword2.length() - 1);
        }

        WechatUtils.TemplateCrawlingCompleteInfo screenInfo = new WechatUtils.TemplateCrawlingCompleteInfo();

        screenInfo.setFirst("您好，简历下载完成。");
        screenInfo.setKeyword1(keyword1);
        screenInfo.setKeyword2(keyword2);
        screenInfo.setKeyword3(task.getCreateTime());
        screenInfo.setRemark("点击详情，查看下载简历。");

        return screenInfo;
    }

    private String send(WechatUtils.TemplateInfo templateInfo) {
        WechatUtils.sendTemplateMessage(WechatUtils.getAccessToken(), templateInfo);
        return null;
    }

}
